package org.xxl.views.base 
{
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.utils.getQualifiedClassName;
	import org.as3commons.lang.StringUtils;
	import org.as3commons.reflect.Accessor;
	import org.as3commons.reflect.Field;
	import org.as3commons.reflect.Type;
	import org.xxl.views.core.ITempleteComponent;
	
	/**
	 * ...
	 * @author XXL
	 */
	public class TempleteComponent implements ITempleteComponent 
	{
		protected static const INTERFACENAME:String = StringUtils.replace(getQualifiedClassName(ITempleteComponent), "::", ".");
		protected var _skin:DisplayObject;
		
		public static const __ReflectionFun:Function = function(skin:DisplayObject):void
		{
			var properties:Array = Type.forInstance(this).properties;
			for each(var property:Field in properties)
			{
				if (property is Accessor && (property as Accessor).writeable == false)
				{
					continue;
				}
				if (!(skin is DisplayObjectContainer))
				{
					continue;
				}
				var skinProperty:DisplayObject = (skin as DisplayObjectContainer).getChildByName(property.name);
				if (property.type.interfaces.indexOf(INTERFACENAME) >= 0)
				{
					var instance:ITempleteComponent = new (property.type.clazz);
					instance.buildTemplete(skinProperty);
					this[property.name] = instance;
				}
				else if (skinProperty is DisplayObject)
				{
					try
					{
						this[property.name] = skinProperty;
					}
					catch (e:Error)
					{
						trace("无法设置" + property.name + e.message);
					}
				}
			}
		};
		
		/* INTERFACE org.xxl.views.core.ITempleteComponent */
		
		public function buildTemplete(skin:DisplayObject):void 
		{
			this._skin = skin;
			__ReflectionFun.call(this, skin);
			skin.cacheAsBitmap = true;
		}
		
		public function get skin():DisplayObject 
		{
			return _skin;
		}
		
	}

}